﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Web.Services;

public partial class DisplayWeek: System.Web.UI.Page
{
    List<Game> gamesForWeek;
    List<UserPick> userPicks;
    User user;
    List<GameControl> gcs = new List<GameControl>();
    protected void Page_Load(object sender, EventArgs e)
    {
        //Helper.MakeSeason();

        if (!Page.IsPostBack)
        {
            Week week;
            var weekQuery = Request.QueryString["Week"];
            var seasonQuery = Request.QueryString["Season"];

            if (weekQuery != null && seasonQuery != null)
                week = DataBase.Weeks.GetWeek(Request.QueryString["Week"], DataBase.Seasons.GetSeasonWithID(seasonQuery));
            else if (seasonQuery != null)
                week = DataBase.Weeks.GetSeasonsCurrentWeek(seasonQuery);
            else
                week = DataBase.Weeks.GetCurrentWeek();

             if (Session["userID"] != null)
                        user = DataBase.Users.GetUserWithID(Session["userID"].ToString());

            if (week != null)
            {
                this.gamesForWeek = GameScraper.UpdateGames(week);
                userPicks = DataBase.UserPicks.GetAllUserPicksForWeek(week);


                foreach (Game game in gamesForWeek)
                {
                    var gamePicks = (from u in userPicks
                                     where u.GameID == game.ID
                                     select u).ToList();

                    GameControl gc = (GameControl)Page.LoadControl("~/GameControl.ascx");

                    if (user != null)
                    {
                        gc.Init(game, gamePicks, user);
                    }
                    else
                        gc.Init(game, gamePicks);


                    gcs.Add(gc);
                    gameControls.Controls.Add(gc);
                }

                GenerateWeekPicker(week);

                GenerateRankings(week);
                LoadSmackTalk(week, user);
               // GenerateWeeks(week);
              //  GenerateSeasons(week.WeekSeason);
                SetAutoRefersh();
            }
        }
    }

    private void GenerateWeekPicker(Week week)
    {
        weekPicker.GenerateSeasonsandWeeks(week);
    }

    private void LoadSmackTalk(Week week, User user)
    {
        smacktalk.LoadMessages(week, user);
    }
    //private void GenerateSeasons(Season selectedSeason)
    //{  
    //    seasonsControl.GenerateSeasons(selectedSeason, "DisplayWeek.aspx");
    //}

    private void SetAutoRefersh()
    {
        int inGameCount = (from g in gamesForWeek
                           where g.GameState == Game.State.InGame
                           select g).Count();

        if (inGameCount > 0)
            Response.AppendHeader("Refresh", "120");
    }

    private void GenerateRankings(Week week)
    {
        dgRankings.RowDataBound += new GridViewRowEventHandler(GridView1_RowDataBound);
        List<UserRanking> rankings = DataBase.Rankings.GetWeekStandings(week.ID.ToString());

        bool hasWinner = (from u in rankings
                          where u.Winner == true
                          select u).Count() > 0;

        if(!hasWinner)
           rankings = Helper.LookForLosers(rankings, week);

        dgRankings.DataSource = rankings;
        dgRankings.DataBind();

    }

    void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Nullable<bool> canWin = ((UserRanking)e.Row.DataItem).Winner;

            if (canWin == null)
            {
                e.Row.BackColor = Color.FromName("#71cf90");
            }
            else if(canWin == false)
            {
                e.Row.BackColor = Color.FromName("#ff7373");
            }
            else if (canWin == true)
            {
                e.Row.BackColor = Color.FromName("#6cf066");
            }
        }
    }


    protected void Page_LoadComplete(object sender, EventArgs e)
    {

        foreach (GameControl gc in gcs)
        {
            gc.LoadGame();
        }

    }

    protected void MaintainScroll(GameControl gc)
    {
        string script = @" window.onload = function Maintain()
                              {var con = document.getElementById('" + gc.ClientID + "_gameControl" + "');con.scrollIntoView(); }";
        this.ClientScript.RegisterStartupScript(this.GetType(), "Maintain", script, true);
    }

    //private void GenerateWeeks(Week week)
    //{
    //    string normalWeek = "week";
    //    string selectedWeek = "selectedWeek";
    //    var weekcount = DataBase.Weeks.GetSeasonsWeekCount(week.WeekSeason);
    //    for (int i = 1; i <= weekcount; i++)
    //    {
    //            string cssClass = (week.Number == i ? selectedWeek : normalWeek);
    //            weekNumbers.Controls.Add(new LiteralControl("<a href=\"DisplayWeek.aspx?Season="+ week.WeekSeason.ID + "&Week=" + i + "\" class=\"" + cssClass + "\">"));
    //            weekNumbers.Controls.Add(new LiteralControl(i.ToString()));
    //            weekNumbers.Controls.Add(new LiteralControl("</a>"));
    //    }
    //}


    [WebMethod]
    public static void makePick(string gameID, string teamID, string userID)
    {
     
        UserPick userPick = new UserPick()
        {
            ChosenTeamID = int.Parse(teamID),
            GameID = int.Parse(gameID),
            UserID = int.Parse(userID)
        };

        DataBase.UserPicks.InsertUserPick(userPick);

    }
}